/*
 moxl - Modular XML Library
 Copyright (c) 2007, Malcolm Sparks

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package moxl.relaxng.simplification.normalization.names;

import moxl.dom.MoxlAttribute;
import moxl.dom.MoxlAttributeMap;
import moxl.dom.DefaultXmlNamespace;
import moxl.dom.MoxlNode;
import moxl.dom.MoxlNodeVisitor;
import moxl.dom.XmlNamespace;
import moxl.dom.ethereal.EtherealElement;
import moxl.dom.mutable.MutableElement;
import moxl.relaxng.schema.RelaxNgSchemaElementType;

public class NameClassNormalizingVisitor implements MoxlNodeVisitor
{
	public void startNode(MoxlNode node)
	{
		if (node instanceof MutableElement)
		{
			MutableElement el = (MutableElement) node;
			if (el.getName().equals(RelaxNgSchemaElementType.element.getName()) || el.getName().equals(RelaxNgSchemaElementType.attribute.getName()))
			{
				MoxlAttributeMap attributeMap = el.getAttributeMap();
				// Check it has a name attribute, if so, remove it and add a name element
				MoxlAttribute nameAttribute = attributeMap.get("name");
				if (nameAttribute != null)
				{
					EtherealElement newEl = new EtherealElement(RelaxNgSchemaElementType.name.getName());
					String value = nameAttribute.getValue();
					XmlNamespace namespace = null;
					int colon = value.indexOf(":");
					String content = null;
					if (colon != -1)
					{
						String prefix = value.substring(0, colon);
						content = value.substring(colon + 1);
						namespace = el.getNamespaceContext().lookupNamespace(prefix);
					}
					else
					{
						namespace = DefaultXmlNamespace.getInstance();
						content = value;
					}
					String nsUri = namespace.getUri();
					newEl.setAttribute("ns", nsUri);
					newEl.setContent(content);
					((MutableElement) node).insertChild(newEl);
					attributeMap.removeAttribute(nameAttribute);
				}
				else
				{
					throw new UnsupportedOperationException("Make sure element has at least a name element");

				}
			}
		}
	}

	public void endNode(MoxlNode node)
	{
	}

}
